<template>
  <view class="content">

    <view class="width95 title">
      {{ dynamicTitle }}

      <image class="ceshi" src="@/static/定位.png"></image>
    </view>

    <!-- 轮播图 -->
    <view class="banner-image">
      <!-- <image class="banner-image" src="static/banner.png"></image> -->
      <u-swiper :list="imgList" height="220" mode="dot" border-radius="20"></u-swiper>
    </view>

    <!-- 搜索框 -->
    <!-- <navigator class="width95" url="search">
      <view>
        <input class="input"  placeholder="输入店铺" placeholder-style="color:#b8b8b8" />
      </view>
    </navigator> -->

    <!-- 选项 -->
    <view class="width95">
      <view class="width45 d-row d-jc-between" style="gap: 30rpx;">
        <view :class="{active: activeTabIndex == index}"
              v-for="(item,index) in canteenName" :key="index" @tap="handleTab(index)">
          <view class="title-name">{{ item }}</view>
          <view :class="{titleBottom: activeTabIndex == index}"></view>
        </view>
      </view>
    </view>

    <!-- 店铺 -->
    <view class="width90 d-row d-jc-around" style="margin-top: 30rpx;height: 180rpx;"
          v-for="(item,index) in sList" :key="index" @tap="intoDetails(item)">
      <view class="s-head d-clo d-jc-centen d-ai-centen ">
        <image class="s-head-img" :src="item.avatar"></image>
      </view>
      <view class="s-detail d-clo d-jc-around">
        <view class="font-bold font32">{{ item.userName }}</view>
        <view class="font28 gray3">月销{{ 99 }}</view>
        <view class="d-row d-jc-between gray3">
          <view>当前预约排队人数：{{ 80 }}人</view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      title: '',
      canteenList: [],
      canteenName: [],
      deptId: [],
      activeTabIndex: 0,
      imgList: [{
        image: '/static/1.png'
      },
        {
          image: '/static/2.png'
        },
        {
          image: '/static/3.png'
        }
      ],
      sList: [],
      selectedCampus: localStorage.getItem('selectedCampus')
    }
  },
  computed: {
    dynamicTitle() {
      const campusCode = this.selectedCampus;
      switch (campusCode) {
        case '101':
          return '华北水利水电大学（龙子湖校区）';
        case '102':
          return '华北水利水电大学（花园校区）';
        case '200':
          return '华北水利水电大学（江淮校区）';
        default:
          return '请选择所在校区';
      }
    }
  },
  onLoad() {
    this.title = this.dynamicTitle;
    this.getCanteenList()
        .then(() => {
          if (this.canteenList.length > 0) {
            this.activeTabIndex = 0; // 确保在数据加载后设置
            this.handleTab(this.activeTabIndex);
          } else {
            console.error('canteenList 数据为空，无法加载');
          }
        })
        .catch(err => {
          console.error('获取食堂列表失败:', err);
        });
  },
  watch: {
    selectedCampus(newVal) {
      this.title = this.dynamicTitle; // 监听 selectedCampus 变化更新标题
    },
    // watch 监听器,监听到数据发生变化时执行
    activeTabIndex: async function (val) {
      if (this.canteenList[val]) { // 确保索引有效
        const type = this.canteenList[val].value;
        await this.getIndexList(type);
      } else {
        console.error('无效的 activeTabIndex:', val);
      }
    }
  },
  methods: {
    // 加载选中食堂窗口列表
    handleTab(index) {
      // 1. 更新选中状态
      this.activeTabIndex = index;

      // 2. 获取当前选中的 deptName
      const deptName = this.canteenName[index];
      const deptId = this.deptId[index];

      // 3. 构建查询参数（GET 请求参数需附加在 URL 后）
      const queryParams = `deptId=${encodeURIComponent(deptId)}&deptName=${encodeURIComponent(deptName)}`;

      // 4. 发送 GET 请求（移除 headers 和 data）
      uni.request({
        url: `http://127.0.0.1:8080/user/user/business/list?${queryParams}`,
        method: 'GET',
        success: (res) => {
          // 根据后端返回的 TableDataInfo 结构处理数据
          // 假设数据在 res.data.rows 或 res.data.list 中
          this.sList = res.data.rows || [];
          console.log('店铺列表更新:', this.sList);
        },
        fail: (err) => {
          console.error('请求失败:', err);
        }
      });
    },
    async getIndexList(type) {
      console.log("获取" + type + "数据列表")
    },
    intoDetails(item) {
      uni.navigateTo({
        url: '../store/index?id=' + item.userId + '&name=' + item.userName + "&headImg=" + item.avatar + '&phone=' + item.phone + "&address=" + item.parentName + '' + item.deptName,
        animationType: 'pop-in',
        animationDuration: 2000
      })
    },
    getCanteenList() {
      return new Promise((resolve, reject) => { // 返回 Promise
        // 动态获取 selectedCampus
        // 优先从 localStorage 获取，否则使用 selectedCampus
        const campusId = localStorage.getItem('selectedCampus') || this.selectedCampus;
        const url = `http://127.0.0.1:8080/user/user/business/canteen/${campusId}`;

        console.log("获取" + campusId + "数据列表")

        uni.request({
          url: url,
          success: (res) => {
            this.canteenList = res.data.data;
            this.canteenName = res.data.data.map(item => item.deptName);
            this.deptId = res.data.data.map(item => item.deptId);
            resolve(); // 数据加载完成
          },
          fail: (err) => {
            reject(err); // 处理错误
          }
        });
      });
    }
  }
}
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.title {
  font-size: 30rpx;
  font-weight: bold;
  margin-top: 10rpx;
  display: flex;
  //gap: 4px;
  align-items: center;
}

.banner-image {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
  width: 95%;
  border-radius: 0 0 50rpx 50rpx;
}

.input {
  background-color: #f7f7f7;
  border-radius: 10rpx;
  padding: 20rpx;
}

.title-name {
  padding: 15rpx 0;
}

.active {
  font-weight: bold;
  color: #007AFF;
}

.titleBottom {
  margin: 0 auto;
  width: 60%;
  border-bottom: 5rpx solid #007AFF;
}

.s-head {
  flex: 1;
}

.s-head-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
}

.s-detail {
  flex: 3;
}

.ceshi {
  width: 30px; /* 宽度设为 200px */
  height: 30px; /* 高度设为 200px */

  object-fit: cover; /* 或 contain */
}
</style>
